package com.intellekt.ecert.login.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.intellekt.ecert.domain.Constantes;
import com.intellekt.ecert.domain.UsuarioVO;
import com.intellekt.ecert.login.service.LoginService;
import com.intellekt.ecert.menu.action.MenuBuilder;
import com.opensymphony.xwork2.ActionSupport;

@Results({ @Result(name = "input", location = "login.jsp"), @Result(name = "success", location = "welcome", type = "tiles"), @Result(name = "error", location = "error.jsp") })
public class LoginAction extends ActionSupport implements SessionAware, RequestAware {

	private static final long serialVersionUID = -8672292551232357038L;

	private static final Logger log = Logger.getLogger(LoginAction.class);

	@Autowired
	protected LoginService service;

	protected Map<String, Object> session;

	@SuppressWarnings("rawtypes")
	private Map request;

	private String username;
	private String password;
	private String forgotPwdUrl;
	private String changePwdUrl;

	public String input() throws Exception {
		if (log.isInfoEnabled()) {
			log.info("input...");
		}
		return INPUT;
	}

	private boolean validaRequeridos() {
		boolean valido = true;
		if (StringUtils.isBlank(username)) {
			addFieldError("username", getText("login.usuario.requerido"));
			valido = false;
		}
		if (StringUtils.isBlank(password)) {
			addFieldError("password", getText("login.password.requerido"));
			valido = false;
		}

		return valido;
	}

	@SuppressWarnings("unchecked")
	public String execute() throws Exception {
		if (log.isInfoEnabled()) {
			log.info("execute...");
		}

		String result = INPUT;

		if (!validaRequeridos()) {
			return result;
		}

		username = username.toUpperCase();

		try {

			UsuarioVO user = service.getUsuarioPorUsername(username, password);
			if (user != null && user.isVigente()) {
				user.setIdMenuMap(service.getPantallasPorRol(user.getRolId()));
				new MenuBuilder().buildMenuForUser(user);
				session.put(Constantes.USUARIO, user);

				request.put("show", "true");
				result = SUCCESS;
			} else if (user != null) {
				addFieldError("msg", getText("login.usuario.noVigente"));
			} else {
				addFieldError("msg", getText("login.usuario.noExiste"));
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			addFieldError("msg", getText("login.error"));
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public UsuarioVO dummy() throws Exception {
		if (log.isInfoEnabled()) {
			log.info("dummy...");
		}

		UsuarioVO user = new UsuarioVO();
		user.setUserId(0);
		user.setUsername("cliff");
		user.setNombre("Cliff Burton");
		user.setRol("Test");
		user.setRolId("a");
		user.setVigente(true);
		Map<String, String> mapa = new HashMap<String, String>();
		mapa.put("1", "usuarios");
		mapa.put("2", "roles");
		mapa.put("3", "parametros");
		mapa.put("4", "enrolamiento");
		mapa.put("5", "roles");
		user.setIdMenuMap(mapa);

		session.put("USER", user);
		request.put("show", "true");

		if (log.isDebugEnabled()) {
			log.debug("sending 2 welcome...");
		}

		return user;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@SuppressWarnings("rawtypes")
	public void setRequest(Map request) {
		this.request = request;
	}

	@SuppressWarnings("rawtypes")
	public final Map getRequest() {
		return request;
	}

	public final Map<String, Object> getSession() {
		return session;
	}

	public final String getUsername() {
		return username;
	}

	public final void setUsername(String username) {
		this.username = username;
	}

	public final String getPassword() {
		return password;
	}

	public final void setPassword(String password) {
		this.password = password;
	}

	public String getForgotPwdUrl() {
		return forgotPwdUrl;
	}

	public String getChangePwdUrl() {
		return changePwdUrl;
	}

}
